package com.alander.nexusgo.framework.mysql.starter.page;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.List;

public class PageUtils {

    private static final int DEFAULT_PAGE_NUM = 1;
    private static final int DEFAULT_PAGE_SIZE = 10;
    private static final int MAX_PAGE_SIZE = 1000;

    public static void startPage(PageDomain pageDomain) {
        int pageNum = pageDomain == null || pageDomain.getPageNum() == null ? DEFAULT_PAGE_NUM : pageDomain.getPageNum();
        int pageSize = pageDomain == null || pageDomain.getPageSize() == null ? DEFAULT_PAGE_SIZE : pageDomain.getPageSize();
        pageSize = clampPageSize(pageSize);
        PageHelper.startPage(pageNum, pageSize);
    }

    public static void startPage(Integer pageNum, Integer pageSize) {
        int pn = pageNum == null ? DEFAULT_PAGE_NUM : pageNum;
        int ps = pageSize == null ? DEFAULT_PAGE_SIZE : pageSize;
        ps = clampPageSize(ps);
        PageHelper.startPage(pn, ps);
    }

    public static void startPage(Integer pageNum, Integer pageSize, String orderBy) {
        startPage(pageNum, pageSize);
        if (orderBy != null && !orderBy.isBlank()) {
            PageHelper.orderBy(sanitizeOrderBy(orderBy));
        }
    }

    public static void startPage(PageDomain pageDomain, String orderBy) {
        startPage(pageDomain);
        if (orderBy != null && !orderBy.isBlank()) {
            PageHelper.orderBy(sanitizeOrderBy(orderBy));
        }
    }

    public static void clearPage() {
        PageHelper.clearPage();
    }

    public static <T> PageInfo<T> getPageInfo(List<T> list) {
        return new PageInfo<>(list);
    }

    private static int clampPageSize(int pageSize) {
        if (pageSize <= 0) return DEFAULT_PAGE_SIZE;
        return Math.min(pageSize, MAX_PAGE_SIZE);
    }

    private static String sanitizeOrderBy(String orderBy) {
    if (orderBy == null || orderBy.isEmpty()) {
        return "";
    }

    // 允许字母、数字、下划线、点、逗号、空格及 ASC/DESC 关键字
    String cleaned = orderBy.replaceAll("[^a-zA-Z0-9_\\s,.]", "");
    // 规范化空格，将多个连续空格替换为单个空格
    cleaned = cleaned.trim().replaceAll("\\s+", " ");
    return cleaned;
}

}